package com.example.project.controller;

import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import com.alibaba.fastjson.JSON;
import com.example.project.annotations.PassToken;
import com.example.project.common.Result;
import com.example.project.dao.TableADao;
import com.example.project.entity.TableA;
import com.example.project.service.TableAServicce;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * Created by Ethan on 2022-08-24 19:20
 */
@PassToken
@RestController
@Slf4j
@RequestMapping("/tableA")
public class TableAController {
    @Autowired
    private TableAServicce servicce;

    /**
     * 导入文件，并加入到数据库
     * @param file
     * @return
     */
    @PostMapping("/add")
    public Result<List<TableA>> addLists(@RequestPart("file") MultipartFile file) {
        ImportParams params = new ImportParams();
        params.setHeadRows(1);
        try {
            List<TableA> list = ExcelImportUtil.importExcel(
                    file.getInputStream(),
                    TableA.class, params);
            for (TableA a : list) {
                servicce.saveTableA(a);
                log.info(a.toString());
            }
            return Result.success(list);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("错误！！！");
        }
    }

    /**
     * 新增一条数据
     * @param tableA
     * @return
     */
    @PostMapping("/addone")
    public Result<String> addOne(@RequestBody TableA tableA) {
        log.info(tableA.toString());
        servicce.saveTableA(tableA);
        return Result.success("添加成功!!!");
    }

    /**
     * 根据ID删除一条数据
     * @param id
     * @return
     */
    @GetMapping("/delete")
    public Result<String> delete(int id) {
        log.info(String.valueOf(id));
        servicce.deleteByName(id);
        return Result.success("删除成功!!!");
    }

    /**
     * 更新数据
     * @param tableA
     * @return
     */
    @PostMapping("/update")
    public Result<String> update(@RequestBody TableA tableA) {
        Result<String> update = update(tableA);
        return Result.success("修改成功!!!");
    }
}
